package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.CustomContentBean
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityAddCustomBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterCustomContent
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import com.gexiaobao.xpopup.util.KeyboardUtils
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.finish
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author      : hxw
 * @Date        : 2024/8/22 10:23
 * @Describe    : 新增自定义内容
 */
class ActivityAddCustom : BaseActivity<BreedingPigeonViewModel, ActivityAddCustomBinding>() {

    private var featherColorList: ArrayList<String> = arrayListOf()
    private var eyeList: ArrayList<String> = arrayListOf()
    private var bloodList: ArrayList<String> = arrayListOf()
    private var title = ""
    private var titleShow = ""
    private var mType = 0
    private var mEditId = 0
    private var isEditOrAdd = false//默认是添加数据

    private val mAdapter: AdapterCustomContent by lazy { AdapterCustomContent(arrayListOf()) }
    private val customList: ArrayList<CustomContentBean> = arrayListOf()

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        title = intent.getStringExtra("title").toString()
        when (title) {
            "羽色" -> {
                mType = 1
                titleShow = getString(R.string.add_custom_color)
                mViewModel.getPgFeatherColor(2)//1-查所有 2-查自定义
            }

            "眼砂" -> {
                mType = 2
                titleShow = getString(R.string.add_custom_eye)
                mViewModel.getPgEye(2)
            }

            "血统" -> {
                mType = 3
                titleShow = getString(R.string.add_custom_breeding)
                mViewModel.getPgBlood(2)
            }

            else -> {}
        }
        mDatabind.tvKey.text = getString(R.string.newly_increased) + title
        mDatabind.includeBar.tvTitle.text = titleShow

        mDatabind.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)

        mAdapter.addChildClickViewIds(R.id.llEditCustomContent, R.id.llDeleteCustomContent)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.llEditCustomContent -> {
                    isEditOrAdd = true
                    mEditId = mAdapter.data[position].id
                    val content = mAdapter.data[position].content
                    mDatabind.etAddCustom.setText(content)
                    mDatabind.etAddCustom.setSelection(content.length)
                    KeyboardUtils.showSoftInput(mDatabind.etAddCustom)
                }

                R.id.llDeleteCustomContent -> {
                    showHintDialog(mAdapter.data[position].content, mAdapter.data[position].id)
                }
            }
        }

        /** 解决软键盘弹出按钮上移 */
        mDatabind.btnSaveAddCustom.viewTreeObserver.addOnGlobalLayoutListener {
            val r = Rect()
            mDatabind.btnSaveAddCustom.getWindowVisibleDisplayFrame(r)

            val screenHeight = mDatabind.btnSaveAddCustom.rootView.height
            val keyboardHeight = screenHeight - r.bottom

            // 根据键盘的状态调整布局的大小
            if (keyboardHeight > screenHeight * 0.15) {
                // 键盘弹出
                val layoutParams = mDatabind.btnSaveAddCustom.layoutParams as LinearLayout.LayoutParams
                layoutParams.setMargins(40, 0, 40, keyboardHeight)
                mDatabind.btnSaveAddCustom.layoutParams = layoutParams
            } else {
                // 键盘收起
                val layoutParams = mDatabind.btnSaveAddCustom.layoutParams as LinearLayout.LayoutParams
                layoutParams.setMargins(40, 0, 40, 70)
                mDatabind.btnSaveAddCustom.layoutParams = layoutParams
            }
        }
    }

    private fun showHintDialog(content: String, id: Int) {
        val dialog = RxDialogDefault(this)
        dialog.setContent(getString(R.string.Confirm_Delete) + content + "?")
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            mViewModel.delCustomInfo(id, mType)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 删除自定义信息 */
        mViewModel.delCustomInfoResult.observe(this) {
            when (title) {
                "羽色" -> mViewModel.getPgFeatherColor(2)//1-查所有 2-查自定义
                "眼砂" -> mViewModel.getPgEye(2)
                "血统" -> mViewModel.getPgBlood(2)
                else -> {}
            }
        }
        /** 编辑自定义信息 */
        mViewModel.editCustomInfoResult.observe(this) {
            intentForFinish()
        }
        /** 自定义血統 */
        mViewModel.addPgBloodResult.observe(this) {
            intentForFinish()
        }
        /** 获取血統列表 */
        mViewModel.getPgBloodResult.observe(this) {
            if (it != null && it.list.isNotEmpty()) {
                customList.clear()
                it.list.forEach { data ->
                    customList.add(CustomContentBean(id = data.id, content = data.blood))
                }
                mAdapter.setList(customList)
                mAdapter.notifyDataSetChanged()
            }
        }
        /** 获取眼砂列表 */
        mViewModel.getPgEyeResult.observe(this) {
            if (it != null && it.list.isNotEmpty()) {
                customList.clear()
                it.list.forEach { data ->
                    customList.add(CustomContentBean(id = data.id, content = data.eye))
                }
                mAdapter.setList(customList)
                mAdapter.notifyDataSetChanged()
            }
        }
        /** 获取羽色列表 */
        mViewModel.getPgFeatherColorResult.observe(this) {
            if (it != null && it.list.isNotEmpty()) {
                customList.clear()
                it.list.forEach { data ->
                    customList.add(CustomContentBean(id = data.id, content = data.featherColor))
                }
                mAdapter.setList(customList)
                mAdapter.notifyDataSetChanged()
            }
        }
        /** 自定义眼砂  */
        mViewModel.addPgEyeResult.observe(this) {
            intentForFinish()
        }
        /** 自定义羽色 */
        mViewModel.addPgColorResult.observe(this) {
            intentForFinish()
        }
    }

    private fun intentForFinish() {
        val intent = Intent()
        intent.putExtra("content", mDatabind.etAddCustom.text.toString().trim())
        finish(intent)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.btnSaveAddCustom) {
            when (it) {
                mDatabind.btnSaveAddCustom -> {
                    if (isEditOrAdd) {
                        editCustomContent()
                    } else {
                        addCustomContent()
                    }
                }

                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    private fun addCustomContent() {
        val content = mDatabind.etAddCustom.text.toString().trim()
        if (content.isEmpty()) {
            RxToast.warning(getString(R.string.please_input_custom_content))
            return
        }
        when (title) {
            "羽色" -> {
                featherColorList.clear()
                featherColorList.add(content)
                showLoading(getString(R.string.loading))
                val map = mapOf("featherColor" to featherColorList)
                val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                mViewModel.addPgFeatherColor(body)
            }

            "眼砂" -> {
                eyeList.clear()
                eyeList.add(content)
                showLoading(getString(R.string.loading))
                val map = mapOf("eye" to eyeList)
                val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                mViewModel.addPgEye(body)
            }

            "血统" -> {
                bloodList.clear()
                bloodList.add(content)
                showLoading(getString(R.string.loading))
                val map = mapOf("blood" to bloodList)
                val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                mViewModel.addPgBlood(body)
            }

            else -> {}
        }
    }

    private fun editCustomContent() {
        val content = mDatabind.etAddCustom.text.toString().trim()
        if (content.isEmpty()) {
            RxToast.warning(getString(R.string.please_input_custom_content))
            return
        }
        showLoading(getString(R.string.loading))
        mViewModel.editCustomInfo(mEditId, content, mType)
    }
}